﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;

namespace AlarmManagePlatform.DataAccess
{
    public class tb_RoleInfo
    {

        internal List<Model.DB.tb_RoleInfo> GetRoleInfoList()
        {
            Relations.DBUtility.SqlServer.SqlDb _SqlDb = null;
            List<Model.DB.tb_RoleInfo> _Result;
            DataTable _DataTable;
            string _SqlScript;
            try
            {
                
                _SqlScript = "Select * From tb_RoleInfo Order By RoleId";
                _SqlDb = Static.Methods.OpenDataBase();
                _DataTable = _SqlDb.RunSqlScript(_SqlScript);
                _Result = DataTableToList(_DataTable);

                return _Result;
            }
            catch (Exception ex)
            {
                throw new Exception("获取角色信息失败，错误信息：" + ex.Message);
            }
            finally
            {
                if (_SqlDb != null)
                    Static.Methods.CloseDataBase(_SqlDb);
            }
        }

        internal Model.DB.tb_RoleInfo GetRoleInfo(string roleId)
        {
            Relations.DBUtility.SqlServer.SqlDb _SqlDb = null;
            List<Model.DB.tb_RoleInfo> _Result;
            DataTable _DataTable;
            string _SqlScript;
            try
            {

                _SqlScript = $"Select * From tb_RoleInfo Where RoleId = {roleId} Order By RoleId";
                _SqlDb = Static.Methods.OpenDataBase();
                _DataTable = _SqlDb.RunSqlScript(_SqlScript);
                _Result = DataTableToList(_DataTable);

                if (_Result.Count > 0)
                {
                    return _Result[0];
                }
                else
                {
                    return null;
                }

            }
            catch (Exception ex)
            {
                throw new Exception("获取角色信息失败，错误信息：" + ex.Message);
            }
            finally
            {
                if (_SqlDb != null)
                    Static.Methods.CloseDataBase(_SqlDb);
            }
        }

        private List<Model.DB.tb_RoleInfo> DataTableToList(DataTable dataTable)
        {
            List<Model.DB.tb_RoleInfo> _Result;
            Model.DB.tb_RoleInfo _Temp;
            try
            {
                _Result = new List<Model.DB.tb_RoleInfo>();
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    _Temp = new Model.DB.tb_RoleInfo();
                    _Temp.RoleId = int.Parse( dataTable.Rows[i]["RoleId"].ToString());
                    _Temp.Name = dataTable.Rows[i]["Name"].ToString();
                    _Result.Add(_Temp);
                }
                return _Result;
            }
            catch (Exception ex)
            {
              throw new Exception("将Datatable转换成List<Model.DB.tb_RoleInfo>有异常：" + ex.ToString());
            }
        }
    }
}
